package com.example.server.config;

import com.google.common.collect.Lists;
import com.google.common.net.HttpHeaders;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;

import static com.google.common.collect.Lists.newArrayList;

@Profile("!prod")
@Configuration
@EnableSwagger2
public class SwaggerConfiguration {
    /**
     * 创建获取api应用
     * @return
     */
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.server"))
                .paths(PathSelectors.any())
                .build();
    }

    @Bean
    public Docket authenticatedApiDocket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("authenticated")
                .useDefaultResponseMessages(false)
                .securitySchemes(apiKey())
                .securityContexts(securityContext())
                .select()
                .build();
    }

    private List<ApiKey> apiKey() {
        return newArrayList(new ApiKey("JWT", HttpHeaders.AUTHORIZATION, "header"));
    }

    private List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        return Lists.newArrayList(
                new SecurityReference("JWT", authorizationScopes));
    }


    private List<SecurityContext> securityContext() {
        return newArrayList(
                SecurityContext.builder()
                        .securityReferences(defaultAuth())
                        .forPaths(PathSelectors.any())
                        .build()
        );
    }

    /**
     * 配置swagger文档显示的相关内容标识(信息会显示到swagger页面)
     * @return
     */
    private ApiInfo apiInfo() {
        Contact contact = new Contact("codingstyle", "", "codingstyle.cn");
        return new ApiInfo(
                "test",
                "test开放的接口",
                "v1.0",
                "",
                contact,
                "",
                "",
                new ArrayList<>()
        );
    }
}
